package cn.dota2info.elk.utils;


import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtils<T>{
    /**
     * 将map里的值封装到指定对象中
     * @param sourceAsMap
     * @param c
     * @param id
     * @return
     * @throws Exception
     * @throws InstantiationException
     */
    public static Object map2Object(Map<String,Object> sourceAsMap,Class c,String id) throws Exception, InstantiationException {
        Object o=c.newInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Field idfield=c.getDeclaredField("id");
        idfield.setAccessible(true);
        idfield.set(o,id);
        Field [] f=c.getDeclaredFields();
        Field.setAccessible(f,false);
        for (String in : sourceAsMap.keySet()) {
            Object str = sourceAsMap.get(in);
            for(Field field:f){
                field.setAccessible(true);
                String name = field.getName();
                if (name.equals(in)) {
                    if(field.getGenericType().toString().equals("class java.util.Date") ){
                        try{
                            field.set(o,sdf.parse((String) str));
                        }catch (Exception e){
                            field.set(o,null);
                        }

                    }else{
                        field.set(o,str);
                    }
                }
            }
        }
        return o;
    }

    public static Map<String,Object> Object2Map(Object o) throws IllegalAccessException {
        Map<String, Object> jsonMap = new HashMap<>();
        Field[] f = o.getClass().getDeclaredFields();
        Field.setAccessible(f,true);
        for (Field field : f) {
            String name = field.getName();
            if (!name.equals("id")) {
                jsonMap.put(name,field.get(o));
            }
        }
        return jsonMap;

    }
    public  List<T>  hits2List(SearchHits hits,Class c) throws Exception {
        List<T> objects=new ArrayList<>();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            T obj= (T) MapUtils.map2Object(sourceAsMap,c,hit.getId());
            objects.add(obj);
        }
        return objects;
    }

}
